package cn.hxzy.course.controller;


import cn.hxzy.common.domain.Task;
import cn.hxzy.common.domain.User;
import cn.hxzy.common.domain.vo.TaskVo1;
import cn.hxzy.common.listenr.StudentListener;
import cn.hxzy.common.response.R;
import cn.hxzy.course.service.TaskService;
import cn.hxzy.common.util.ThreadLocalUtil;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author niuyi
 * @since 2024-06-22
 */
@RestController
@RequestMapping("/task")
public class TaskController {

    @Autowired
    private TaskService taskService;



    @GetMapping("/getTaskListByTeacherId")
    public List<Task> getTaskListByTeacherId(int taskId) {
        return taskService.selectList(taskId);
    }

    /**
     * 搜索框搜索作业
     * @param taskName
     * @return
     */
    @GetMapping("/selectTask/{taskName}/{courseId}")
    public R<List<Task>> selectVideo(@PathVariable String taskName, @PathVariable Integer courseId) {
        List<Task> tasks = taskService.selectTask(taskName,courseId);
        if (tasks!=null){
            return R.success(tasks);
        }
        return null;
    }
    //新增和修改作业
    @PostMapping("saveOrUpdate")
    public R saveOrUpdate(@RequestBody Task task){
        Task task1 = new Task();
        if (task.getTaskName() != null || task.getTaskFile()!=null) {
            task1.setTaskName(task.getTaskName());
            task1.setTaskId(task.getTaskId());
            User user = ThreadLocalUtil.getUser();
            Long userId = user.getUserId();
            if (userId >= Integer.MIN_VALUE && userId <= Integer.MAX_VALUE) {
                task1.setTeacherId(userId.intValue());
            } else {
                throw new IllegalArgumentException("The user ID is out of the range for an integer.");
            }
            task1.setSectionId(task.getSectionId());
            if (task.getTaskInfo() != null) {
                task1.setTaskInfo(task.getTaskInfo());
                boolean b = taskService.saveOrUpdate(task1);
                return R.success("编辑成功");
            }
        }
        return R.error(401,"作业题目不能为空");
    }

    //查询作业
    @GetMapping("/getTask")
    public R getTask(int sectionId){
        List<Task> list = taskService.getList(sectionId);
        return R.success(list);
    }
    //根据作业ID获取作业详情
    @GetMapping("getByTaskId")
    public R getByTaskId(@RequestParam("taskId") Integer taskId){
        Task task = taskService.getById(taskId);
        return R.success(task);
    }


    @GetMapping("/getTaskNum")
    public R getVideoNum(@RequestParam("courseId") Long courseId) {
        return R.success(taskService.selectCount(courseId));
    }


    @PostMapping("/importData")
    //TODO
    public void importData(@RequestParam("file") MultipartFile file,@RequestParam("sectionId") int sectionId) {
        try {
            //获取文件的输入流
            InputStream inputStream = file.getInputStream();
            List<TaskVo1> list = EasyExcel.read(inputStream) //调用read方法
                    //注册自定义监听器，字段校验可以在监听器内实现
                    .registerReadListener(new StudentListener())
                    .head(TaskVo1.class) //对应导入的实体类
                    .sheet(0) //导入数据的sheet页编号，0代表第一个sheet页，如果不填，则会导入所有sheet页的数据
                    .headRowNumber(1) //列表头行数，1代表列表头有1行，第2行开始为数据行
                    .doReadSync(); //开始读Excel，返回一个List<T>集合，继续后续入库操作
            User user = ThreadLocalUtil.getUser();
            System.out.println(user);
            Long userId = user.getUserId();
            // TODO 导入后的处理逻辑
            for (int i = 0; i < list.size(); i++) {
                Task task=new Task();
                task.setTaskName(list.get(i).getTaskName());
                task.setSectionId(sectionId);
                task.setTeacherId(userId.intValue());
                task.setTaskInfo(list.get(i).getTaskInfo());
                taskService.save(task);
            }

        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }



    /**
     * 设置响应结果
     *
     * @param response    响应结果对象
     * @param rawFileName 文件名
     * @throws UnsupportedEncodingException 不支持编码异常
     */
    private void setExcelResponseProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {

        //设置内容类型
        response.setContentType("application/vnd.vnd.ms-excel");
        //设置编码格式
        response.setCharacterEncoding("utf-8");
        //设置导出文件名称（避免乱码）
        String fileName = URLEncoder.encode(rawFileName.concat(".xlsx"), "UTF-8");
        // 设置响应头
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
    }


    /**
     * 查询当前小节作业
     *
     * @param sectionId
     * @return
     */
    @GetMapping("/selectTaskList")
    public R<List<Task>> selectTaskList(Integer sectionId) {
        List<Task> tasks = taskService.selectTaskList(sectionId);
        System.out.println(tasks);
        if (tasks != null) {
            return R.success(tasks);
        }
        return null;
    }

    //删除作业
    @DeleteMapping("/deleteTask")
    public R deleteTask(@RequestParam("taskId") Integer taskId){
        int i = taskService.deleteTask(taskId);
        if (i>0){
            return R.success("删除成功");
        }
        return R.error(401,"删除失败");
    }
}

